<template>
    <Row>
        <Col span="22" offset="1">
            <Form aria-readonly ref="CreditContract" :model="CreditContract" :rules="ruleValidate" :label-width="135" :style="{marginTop: '30px'}">
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="借条编码">
                            <Input v-model="CreditContract.NumCode" readonly placeholder="借条编码由系统自动生成" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                
                <Divider orientation="left">借条信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="项目经理" prop="ProjectManager">
                            <Input  v-model.trim="CreditContract.ProjectManager" placeholder="例如：毛XX" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="身份证号" prop="ProjectManagerID">
                            <Input  v-model.trim="CreditContract.ProjectManagerID" placeholder="例如：330681xxxxxxxx1678" ></Input>
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="借款金额(小写)" prop="Amount">
                            <Input v-model.number="CreditContract.Amount" placeholder="实际发生的金额" >
                                <span slot="suffix"><i>元</i ></span>
                                <Icon type="logo-yen" slot="prefix" />
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="借款金额(大写)" prop="BigAmount">
                            <Input v-model.trim="BigMoney" readonly placeholder="实际发生的金额" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10" offset="2">
                        <FormItem label="借款利率" prop="FreezeRate">
                            <Input v-model.number="CreditContract.FreezeRate" placeholder="例如：6、10、12" >
                                <Select v-model="CreditContract.FreezeRateType" slot="prepend" style="width: 80px">
                                    <Option value="DAY">日</Option>
                                    <Option value="MONTH">月</Option>
                                    <Option value="YEAR">年</Option>
                                </Select>
                                <span slot="append"><i>%</i ></span>
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="签订时间" prop="SignDate">
                            <DatePicker v-model.trim="CreditContract.SignDate" format="yyyy-MM-dd"  type="date" placeholder="请选择时间！" style="width: 100%"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="10" offset="2">
                        <FormItem label="应确认利息" prop="FreezeInterest">
                            <Input readonly v-model.number="CreditContract.FreezeInterest" placeholder="例如：564612.45" >
                                <span slot="suffix"><i>元</i ></span>
                            </Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="借条落实人" prop="CreditContractOperator">
                            <Input v-model.trim="CreditContractOperator" disabled placeholder="例如：赵烨" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="分管项目财务" prop="Accountant">
                            <Input v-model.trim="CreditContract.Accountant" placeholder="例如：赵烨" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2">
                        <FormItem label="备注" prop="Remark">
                            <Input v-model="CreditContract.Remark" maxlength="250" type="textarea" :autosize="{minRows: 5,maxRows: 5}" show-word-limit placeholder="请输入冻结资金备注！"></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Divider orientation="left">冻结信息</Divider>
                <Row>
                    <Col span="20" offset="2">
                        <ButtonGroup shape="circle" style="margin-left:25px" >
                            <Button type="primary" @click.native="FreezeMoneyDialog=true">选择</Button>
                            <Button type="error">删除</Button>
                        </ButtonGroup>
                        <Table 
                            :columns="FreezeListColumns" 
                            :data="CreditContract.FreezeList" 
                            style="border-radius: 15px;margin-top: 20px"
                            border 
                            show-summary 
                            :summary-method="SumFreezeList" 
                            height="350">
                        </Table>
                    </Col>
                    <Modal
                        v-model="FreezeMoneyDialog"
                        title="请选择相关冻结款"
                        fullscreen
                        ok-text="选择"
                        @on-ok="ChoiceFreezeMoney"
                        @on-cancel="ChoiceCancel">
                        <FreezeMoney ref="FreezeList" />
                    </Modal>
                </Row>
                <Divider orientation="left">附件信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="">
                            <Button @click="CreateCreditContract" type="primary">生成借条确认书</Button>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="">
                            <Button @click="CreateCreditContract" type="warning">生成利息确认书</Button>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2">
                        <FormItem label="借条档案" prop="Summary">
                            <Upload
                                :headers="UploadHeader"
                                type="drag"
                                :data="UploadParmas"
                                :paste="true"
                                :action="UploadURL"
                                :before-upload="BeforeUpload"
                                :on-remove="RemoveUpload"
                                accept=".pdf">
                                <div style="padding: 20px 0;text-align:center">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                    <p style="text-align:center;font-size:small;color:black">单击或拖拽至此上传文件</p>
                                </div>
                            </Upload>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2" style="text-align:center;margin-top:58px">
                        <Button type="primary" @click="Submit('CreditContract')">提交</Button>
                        <Button @click="Reset('CreditContract')" style="margin-left: 108px">重置</Button>
                    </Col>
                </Row>
            </Form>
        </Col>
    </Row>
</template>
<script>
import { mapState } from "vuex";
import 
{ 
    CreateCode,
    GetOne,
    Create,
    Update,
    ComputeInterest,
    CheckIDNumber,
    DeleteUploadFile,
} from '@/axios/api/CreditContractAPI'
import { BigMoney } from '@/axios/api/BankAPI'
import { GetOne as GetUser } from '@/axios/api/UsersAPI'
import { getUserInfo,getToken } from '@/store/localStorage/cookies';
import FreezeMoney from '@/views/freeze/FreezeMoney/Index'
import qs from 'qs'

export default {
    computed:{
        ...mapState('creditcontract',[
            'currentCreditContractID',
            'pageIndex',
            'pageSize',
        ])
    },
    components: {
        FreezeMoney
    },
    mounted: function(){
        
        //console.log(this.currentCreditContractID)
        if(this.currentCreditContractID != ''){
            this.$Spin.show();
        }
        setTimeout(() => {
            this.$Spin.hide();
        }, 1000);
        
        if(this.currentCreditContractID != ''){
            GetOne(this.currentCreditContractID).then(res => {
                this.CreditContract.Id = res.Id;
                this.CreditContract.Num = res.Num;
                this.CreditContract.NumCode = res.NumCode;
                this.CreditContract.FreezeBank = res.FreezeBank;
                this.CreditContract.FreezeProject = res.FreezeProject;
                this.CreditContract.FreezeConfirm = res.FreezeConfirm;
                this.CreditContract.CaseCode = res.CaseCode;
                this.CreditContract.CaseStatus = res.CaseStatus;
                this.CreditContract.AccpectCourt = res.AccpectCourt;
                this.CreditContract.Plaintiff = res.Plaintiff;
                this.CreditContract.CourtFreeze = res.CourtFreeze;
                this.CreditContract.JudgmentMoney = res.JudgmentMoney;
                this.CreditContract.FundsType = res.FundsType;
                this.CreditContract.ProjectManager = res.ProjectManager;
                this.CreditContract.ProjectManagerID = res.ProjectManagerID;
                this.CreditContract.Accountant = res.Accountant;
                this.CreditContract.JudgmentTime = res.JudgmentTime;
                this.CreditContract.Remark = res.Remark;
                this.CreditContract.DeadLine = res.DeadLine;
                this.CreditContract.FreezeTime = res.FreezeTime;
                this.CreditContract.UnFreezeTime = res.UnFreezeTime;
                this.CreditContract.FreezeDayCount = res.FreezeDayCount;
                this.CreditContract.FreezeInterest = res.FreezeInterest;
                this.CreditContract.FreezeRate = res.FreezeRate;
                this.CreditContract.FreezeRateType = res.FreezeRateType;
                this.CreditContract.JudgeResult = res.JudgeResult;
                this.CreditContract.Amount = res.Amount;
                this.CreditContract.CreditContractOperatorId = res.CreditContractOperatorId;
                this.CreditContract.CreateTime = res.CreateTime;

                
            });
            
        }
        else{
            CreateCode().then(res => {
                console.log(res);
                this.CreditContract.NumCode = res.toString();
            })

            if(this.CreditContract.Id == '00000000-0000-0000-0000-000000000000'){
                var currentUserInfo = JSON.parse(getUserInfo());
                this.CreditContractOperator = currentUserInfo.Name;
                this.CreditContract.CreditContractOperatorId = currentUserInfo.Id;
            }
            else{
                GetUser(this.CreditContract.CreditContractOperatorId).then(res => {
                    console.log(res);
                    this.CreditContractOperator = res.RealName;
                })
            }
        }
    },
    data () {
        const ValidateIDnumber = (rule,value,callback) => {

            if(value == ''){
                callback(new Error("项目经理身份证号码为必填项！"));
            }
            else if (value.length < 18) {
                callback(new Error('身份证号码不足18位！'));
            }
            else {
                CheckIDNumber({IDNumberStr: value}).then(res => {
                    (res === value) ? callback() : callback(new Error('身份证号码校验不通过！'))
                })
            }

        };
        return {
            CreditContract: {
                Id: '00000000-0000-0000-0000-000000000000',
                Num: 1,
                NumCode: '',
                ProjectManager: '',
                ProjectManagerID: '',
                SignDate: new Date(),
                Accountant: '',
                JudgmentTime: new Date(),
                Remark: '',
                DeadLine: new Date(),
                FreezeTime: new Date(),
                UnFreezeTime: new Date("9999-12-31"),
                FreezeDayCount: 0,
                FreezeInterest: 0.0,
                FreezeRate: 0.0,
                FreezeRateType: "MONTH",
                JudgeResult: 0,
                FundsType: '',
                Amount: 0.0,
                CreditContractOperatorId: '00000000-0000-0000-0000-000000000000',
                CreateTime: new Date(),
                FreezeList: []
            },
            ruleValidate: {
                //Num: [{ type: 'number', message: '只能输入数字', trigger: 'blur' }],
                BankName: [{ required: true, message: '冻结银行为必填项！', trigger: 'blur' }],
                Amount: [{ required: true,type: 'number', message: '只能输入数字', trigger: 'blur' }],
                ProjectCode: [{ required: true, message: '涉案项目编码为必填项！', trigger: 'blur' }],
                ProjectName: [{ required: true, message: '涉案项目名称为必填项！', trigger: 'blur' }],
                ProjectManager: [{ required: true, message: '项目经理为必填项！', trigger: 'blur' }],
                CaseCode: [{ required: true, message: '案号为必填项！', trigger: 'blur' }],
                ProjectManagerID: [{ validator: ValidateIDnumber,required: true, trigger: 'blur'}]
            },
            UploadHeader: {
                Authorization: getToken(),
                "Access-Control-Allow-Origin": '*',
                "Access-Control-Allow-Methods": '*',
                "Access-Control-Allow-Credentials": true
            },
            UploadURL: process.env.VUE_APP_BASE_API + '/CreditContract/UploadImportFile/',
            //UploadURL: process.env.VUE_APP_BASE_NAS + '/entry.cgi',
            UploadParmas: {
                FreezeTime: '',
                ProjectManager: '',
                ProjectManagerID: '',
            },
            NASLoginStatus: false,
            FreezeMoneyDialog: false,
            callmodal: "CreditContract-Sheet",
            CreditContractOperator: '',
            BigMoney:'',
            FreezeListColumns:[{
                type: 'selection',
                width: 60,
                align: 'center'
            },
            {
                type: 'index',
                key: 'Index',
                title: '序号',
                width: 80,
                align: 'center'
            },
            {
                title: '借款人',
                key: 'BankName',
                align:'center',
                minWidth: 300,
                children:[{
                    title: '借款日期',
                    key: 'BankName',
                    align:'center',
                    minWidth: 150,
                    render:(h,params)=>{
                        return h('div',{style: { textAlign:"left" }},params.row.BankName)
                    }
                },{
                    title: '归还日期',
                    key: 'BankName',
                    align:'center',
                    minWidth: 150,
                    render:(h,params)=>{
                        return h('div',{style: { textAlign:"left" }},params.row.BankName)
                    }
                }]
            },
            {
                title: '',
                key: 'BankName',
                align:'center',
                minWidth: 400,
                children:[{
                    title: '借款天数',
                    key: 'BankName',
                    align:'center',
                    minWidth: 100,
                    render:(h,params)=>{
                        return h('div',{style: { textAlign:"left" }},params.row.BankName)
                    }
                },{
                    title: '月利率',
                    key: 'BankName',
                    align:'center',
                    minWidth: 100,
                    render:(h,params)=>{
                        return h('div',{style: { textAlign:"left" }},params.row.BankName)
                    }
                },{
                    title: '本金（元）',
                    key: 'BankName',
                    align:'center',
                    minWidth: 100,
                    render:(h,params)=>{
                        return h('div',{style: { textAlign:"left" }},params.row.BankName)
                    }
                },{
                    title: '利息（元）',
                    key: 'BankName',
                    align:'center',
                    minWidth: 100,
                    render:(h,params)=>{
                        return h('div',{style: { textAlign:"left" }},params.row.BankName)
                    }
                }]
            }]
        }
    },
    watch: {
        'CreditContract.Account'(value){
            if(value != '' && value != null){
                this.AccountTail = value.substr(value.length-4,4);
            }
        },
        'CreditContract.FactFreeze'(value){
            this.CreditContract.Amount = value;
        },
        'CreditContract.Amount'(value){
            if(value != '' && value != null){
                BigMoney(value).then(res => {
                    this.BigMoney = res;
                })
                this.CreditContract.FactFreeze = value;
                ComputeInterest({
                    FreezeTime: this.CreditContract.FreezeTime,
                    UnFreezeTime:  this.CreditContract.UnFreezeTime,
                    Amount:  this.CreditContract.Amount,
                    FreezeRate: this.CreditContract.FreezeRate,
                    FreezeRateType: this.CreditContract.FreezeRateType
                }).then(res => {
                    this.CreditContract.FreezeInterest = res;
                })
            }
        },
        'CreditContract.FreezeRateType'(newValue,oldValue){
            if(oldValue == "DAY" && newValue == "MONTH"){
                this.CreditContract.FreezeRate = Math.round(this.CreditContract.FreezeRate*100*30.0)/100
            }

            if(oldValue == "MONTH" && newValue == "YEAR"){
                this.CreditContract.FreezeRate = Math.round(this.CreditContract.FreezeRate*100*12.0)/100
            }

            if(oldValue == "DAY" && newValue == "YEAR"){
                this.CreditContract.FreezeRate = Math.round(this.CreditContract.FreezeRate*100*360.0)/100
            }

            if(oldValue == "YEAR" && newValue == "MONTH"){
                this.CreditContract.FreezeRate = Math.round(this.CreditContract.FreezeRate*100/12.0)/100
            }

            if(oldValue == "YEAR" && newValue == "DAY"){
                this.CreditContract.FreezeRate = Math.round(this.CreditContract.FreezeRate*10000/360.0)/10000
            }

            if(oldValue == "MONTH" && newValue == "DAY"){
                this.CreditContract.FreezeRate = Math.round(this.CreditContract.FreezeRate*10000/30.0)/10000
            }

            ComputeInterest({
                FreezeTime: this.CreditContract.FreezeTime,
                UnFreezeTime:  this.CreditContract.UnFreezeTime,
                Amount:  this.CreditContract.Amount,
                FreezeRate: this.CreditContract.FreezeRate,
                FreezeRateType: newValue
            }).then(res => {
                this.CreditContract.FreezeInterest = res;
            })
        },
        'CreditContract.FreezeRate'(value){
            ComputeInterest({
                FreezeTime: this.CreditContract.FreezeTime,
                UnFreezeTime:  this.CreditContract.UnFreezeTime,
                Amount:  this.CreditContract.Amount,
                FreezeRate: value,
                FreezeRateType: this.CreditContract.FreezeRateType
            }).then(res => {
                this.CreditContract.FreezeInterest = res;
            })
        },
        'CreditContract.ProjectManager'(value){
            this.FreezeListColumns[3].title = value;
        }
    },
    methods: {
        Submit (name){
            //this.$Message.success('按了OK键');
             this.$refs[name].validate((valid) => {
                if (valid) {
                    if(this.CreditContract.Id == '00000000-0000-0000-0000-000000000000'){
                        this.$Message.success('校验通过!');
                        Create(this.CreditContract).then(res => {
                            if(res > 0){

                                setTimeout(() => {
                                    this.$store.dispatch('creditcontract/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                     this.$Notice.success({
                                        title: '操作提示',
                                        desc: '保存成功！ '
                                    });
                                }, 1000)
                               
                            }
                            else{
                                this.$Notice.error({
                                    title: '操作提示',
                                    desc: '保存失败！ '
                                });
                            }
                        }).catch(err =>{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '保存失败：' + err.data + '!'
                            });
                        })
                        
                    }
                    else{
                        this.$Message.success('校验通过!');
                        
                        Update(this.CreditContract).then(res => {
                            if(res > 0){
                                setTimeout(() => {
                                    this.$store.dispatch('creditcontract/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                     this.$Notice.success({
                                        title: '操作提示',
                                        desc: '更新成功！'
                                    });
                                }, 1000)
                            }
                            else{
                                this.$Notice.success({
                                    title: '操作提示',
                                    desc: '更新失败！'
                                });
                            }
                        }).catch(err =>{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '更新失败：' + err.data + '!'
                            });
                        })
                    }
                    this.ChangeModal();
                } else {
                    this.$Message.error('校验失败!');
                    //this.ChangeModal('CreditContract');
                }
            })
            
        },
        Reset (name){
            this.$refs[name].resetFields();
        },
        ChangeModal (){
            //this.$refs[name].resetFields();
            this.$store.commit('creditcontract/CHANGE_MODAL');
            this.$router.push('/freeze/CreditContract')
        },
        CreateCreditContract(){
            BigMoney(this.CreditContract.Amount).then(res => {

                this.$Spin.show();

                let link = document.createElement("a");

                var CreditContractInfo = {
                    ProjectManager: this.CreditContract.ProjectManager,
                    ProjectManagerID: this.CreditContract.ProjectManagerID,
                    Amount: this.CreditContract.Amount,
                    BigAmount: res,
                    FreezeRate: this.CreditContract.FreezeRate,
                    FreezeRateType: this.CreditContract.FreezeRateType,
                    FreezeTime: this.CreditContract.FreezeTime
                }

                link.href = process.env.VUE_APP_BASE_API + "/CreditContract/CreateWordContract?" + qs.stringify(CreditContractInfo, { arrayFormat: 'brackets' }); // 本窗口打开下载
                //console.log(this.QueryConstraint)

                link.download = "导出文件.docx";

                document.body.appendChild(link);

                link.click();
                
                document.body.removeChild(link);

                this.$Spin.hide();
            })
        },
        RemoveUpload(){
            DeleteUploadFile(this.HandleDataForm.Importfile);
        },
        BeforeUpload(){
            this.UploadParmas.FreezeTime = this.CreditContract.FreezeTime.getTime();
            this.UploadParmas.ProjectManager = this.CreditContract.ProjectManager;
            this.UploadParmas.ProjectManagerID = this.CreditContract.ProjectManagerID;
        },
        ChoiceFreezeMoney(){
            console.log(this.$refs.FreezeList.$refs.Gridtable.selectedRows)
        },
        ChoiceCancel(){
            console.log();
        },
        SumFreezeList(){

        }
    }
}
</script>
<style>
    .auto-complete-item{
        padding: 4px 0;
        border-bottom: 1px solid #F6F6F6;
    }
    .auto-complete-group{
        font-size: 12px;
        padding: 4px 6px;
        margin-bottom:7px;
    }
    .auto-complete-group span{
        color: #666;
        font-weight: bold;
    }
    .auto-complete-group a{
        float: right;
    }
    .auto-complete-count{
        float: right;
        color: #999;
    }
    .auto-complete-more{
        display: block;
        margin: 0 auto;
        padding: 4px;
        text-align: center;
        font-size: 12px;
    }
</style>